package com.nl.controller.web.service;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.AES;
import com.nl.controller.common.util.DateUtils;
import com.nl.controller.web.bean.SmsReportDetail;
import com.nl.controller.web.bean.SmsSummaryInfo;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsMgrTemplateInfoMapper;
import com.nl.controller.web.mapper.SmsReportDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class SmsReportDetailService {

    @Autowired
    private SmsReportDetailMapper smsReportDetailMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private SmsMgrTemplateInfoMapper smsMgrTemplateInfoMapper;

    @SystemServiceLog(description = "短信发送明细查询", value = false)
    public PageInfo<SmsReportDetail> findSmsInfo
            (int page, int limit, String cityId,String countyId, String way, String month, String startTime, String endTime, String mgrId, String mgrName,String regionId, String stationId) {
        Map<String, Object> map = new HashMap<>();
        List<SmsReportDetail> list = new ArrayList<SmsReportDetail>();
        //按时间段查询
        map.put("mgrId", mgrId);
        map.put("mgrName", mgrName);
        map.put("regionId", regionId);
        map.put("stationId", stationId);
        map.put("cityId", cityId);
        map.put("countyId", countyId);
        PageInfo<SmsReportDetail>  pageInfo = new PageInfo<>();
        try {
            if ("0".equals(way)) {
                PageHelper.startPage(page, limit);
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                list = smsReportDetailMapper.findSmsReportDetailDay(map);
                list = this.dimPhoneNum(list);
                pageInfo = new PageInfo<>(list);
                //按照月份查询
            } else if ("1".equals(way)) {
                map.put("month", month);
                map.put("startTime", month + "01");
                map.put("endTime", DateUtils.getLastDayOfMonth(month));
                map.put("startPage", (page - 1) * limit);
                map.put("endPage", (page) * limit);
                list = smsReportDetailMapper.findSmsReportDetailMonth(map);
                list = this.dimPhoneNum(list);
                pageInfo = new PageInfo<>(list);
                pageInfo.setTotal(Long.parseLong(smsReportDetailMapper.findSmsReportDetailCount(map)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信明细查询出现异常：");
            throw e;
        }

        try {
        } catch (Exception e) {
            log.error("短信发送明细查询失败");
            throw new SmsException("短信发送明细查询失败");
        }
        return pageInfo;
    }


    @SystemServiceLog(description = "查询项目下的区域", value = false)
    public List<SmsReportDetail> findRegionInfo(String mgrId, String cityId) {
        Map<String, Object> map = new HashMap<>();
        map.put("mgrId", mgrId);
        map.put("cityId", cityId);
        List<SmsReportDetail> list = new ArrayList<>();
        try {
            list = smsReportDetailMapper.findRegionInfo(map);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询项目下的区域异常：", mgrId);
        }
        return list;
    }

    @SystemServiceLog(description = "查询区域下的基站", value = false)
    public List<SmsReportDetail> findStationInfo(String regionId, String cityId, String mgrId) {
        Map<String, Object> map = new HashMap<>();
        map.put("regionId", regionId);
        map.put("cityId", cityId);
        map.put("mgrId", mgrId);
        List<SmsReportDetail> list = new ArrayList<>();
        try {
            list = smsReportDetailMapper.findStationInfo(map);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询区域下的基站：", regionId);
        }
        return list;
    }


    /**
     * 普通下载方式获取数据表中的数据，导出
     *
     * @param way
     * @param month
     * @param startTime
     * @param endTime
     * @param mgrId
     * @param regionId
     * @param stationId
     * @return
     */

    public JSONArray download(String way, String month, String startTime, String endTime, String mgrId, String mgrName, String regionId, String stationId,String cityId,String countyId) {
        Map<String, Object> map = new HashMap<>();
        JSONArray jsonArray;
        //按时间段方式查询
        if ("0".equals(way)) {
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            //按月方式查询
        } else if ("1".equals(way)) {
            map.put("startTime", month + "01");
            map.put("endTime", DateUtils.getLastDayOfMonth(month));
        }
        map.put("cityId", cityId);
        map.put("countyId", countyId);
        map.put("mgrId", mgrId);
        map.put("mgrName", mgrName);
        map.put("regionId", regionId);
        map.put("stationId", stationId);
        try {
            jsonArray = smsReportDetailMapper.downLoad(map);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信发送明细导出失败");
            throw new SmsException("短信发送明细查询失败");
        }
        return jsonArray;
    }


    @SystemServiceLog(description = "短信发送明细文件下载", value = false)
    public List<File> fileDownload
            (String cityId, String way, String month, String startTime, String endTime, String mgrId) {
        List<File> files = new ArrayList();
        //按月导出
        if ("1".equals(way)) {
            for (String day : this.list(month)) {
                try {
                    files.add(this.getFile(cityId, mgrId, day));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("文件不存在");
                }
            }
        } else {
            try {
                for (String day : this.list(startTime, endTime)) {
                        files.add(this.getFile(cityId, mgrId, day));
                    }
                }catch (Exception e) {
                e.printStackTrace();
                log.error("文件不存在");
            }
            }
        return files;
    }



    public File getFile(String cityId, String mgrId, String day) {
        File file = null;
        StringBuffer fileName = new StringBuffer();
        fileName.append(GlobalConst.PATH);
        fileName.append(cityId);
        fileName.append("/");
        fileName.append(mgrId);
        fileName.append("/");
        fileName.append(mgrId);
        fileName.append(day);
        fileName.append(".xlsx");
        try {
            log.info(fileName.toString());
            file = new File(fileName.toString());
        } catch (Exception e) {
            log.error(fileName.toString() + "文件不存在");
        }
        return file;
    }

    /**
     * 转换时间的格式
     *
     * @param date
     * @return
     */
    private int forMatDate(String date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int result = 0;
        try {
            Date time = formatter2.parse(date);
            String temp = formatter.format(time);
            result = Integer.parseInt(temp);
        } catch (ParseException e) {
            e.printStackTrace();
            log.error("时间转换出错");
        }
        return result;
    }

    /**
     * 一个月内所日期的数组
     */
    private List<String> list(String yearMonth) {
        List<String> list = new ArrayList<>();
        int days = DateUtils.getDayOfMonth(yearMonth);
        for (int i = 1; i <= days; i++) {
            if (i < 10) {
                String day = yearMonth + "0" + i;
                list.add(day);
            } else {
                String day = yearMonth + i;
                list.add(day);
            }
        }
        return list;
    }

    /**
     * 时间段内的时间
     *
     * @param
     * @return
     */
    private List<String> list(String startTime, String endTime) {
        int start = this.forMatDate(startTime);
        int end = this.forMatDate(endTime);
        int result = end - start;
        List<String> list = new ArrayList<>();
        for (int i = 0; i <= result; i++) {
            list.add(String.valueOf(start + i));
        }
        return list;
    }
    
    @SystemServiceLog(description = "发送汇总信息查询", value = false)
    public PageInfo<SmsSummaryInfo> findSummaryInfo
            (int page, int limit, String cityId,String countyId, String mgrId,String mgrName) {
        Map<String, Object> map = new HashMap<>();
        List<SmsSummaryInfo> list = new ArrayList<SmsSummaryInfo>();
        map.put("mgrId", mgrId);
        map.put("cityId", cityId);
        map.put("countyId", countyId);
        map.put("mgrName", mgrName);
        PageInfo<SmsSummaryInfo> pageInfo = null;
        try {
                PageHelper.startPage(page, limit);
                list = smsReportDetailMapper.findSummaryInfo(map);
                for(SmsSummaryInfo smsSummaryInfo:list){
                    smsSummaryInfo.setCityName(smsMgrTemplateInfoMapper.findCityName(cityId));
                    smsSummaryInfo.setCountyName(smsMgrTemplateInfoMapper.findCountyName(countyId));
                }
                System.out.println("list.size():"+list.size());
                pageInfo = new PageInfo<>(list);
                pageInfo.setTotal(smsReportDetailMapper.findSummaryTotal(map));
                for (SmsSummaryInfo smsSummaryInfo : list) {
                	smsSummaryInfo.setProvince("江苏");
				}
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送汇总信息查询出现异常：");
            throw e;
        }
        try {
        	 for (SmsSummaryInfo smsSummaryInfo : list) {
             	smsSummaryInfo.setProvince("江苏");
				}
        } catch (Exception e) {
            log.error("发送汇总信息查询失败");
            throw new SmsException("发送汇总信息查询失败");
        }
        return pageInfo;
    }
    
    /**
     * 模糊手机号码
     * @param list
     * @return
     */
    private List<SmsReportDetail>  dimPhoneNum(List<SmsReportDetail> list) {
        String str = "****";
        StringBuilder sb;
//        SmsReportDetail smsReportDetail1 = new SmsReportDetail();
//        smsReportDetail1.setMsisdn("13022515378");
//        list.add(smsReportDetail1);
        try {
            for (SmsReportDetail smsReportDetail : list) {
                String msisdn = smsReportDetail.getMsisdn();
                if (msisdn!= null) {
                	msisdn = AES.decrypt(msisdn, GlobalConst.SKEY);
                    sb= new StringBuilder(msisdn);
                    sb.replace(3, 7, str);
                    msisdn = sb.toString();
                    smsReportDetail.setMsisdn(msisdn);
                }

                smsReportDetail.setCityName(smsMgrTemplateInfoMapper.findCityName(smsReportDetail.getCityId()));
                smsReportDetail.setCountyName(smsMgrTemplateInfoMapper.findCountyName(smsReportDetail.getCountyId()));

            }
        } catch (Exception e) {
            log.error("解密失败");
            e.printStackTrace();
        }
        return list;
    }
}
